#include <stdio.h>
#include <stdlib.h>
#include <time.h>


double **create_matrix(int rows, int cols){

    double **mat = (double **) malloc(sizeof(double *)*rows);
    int i=0,j=0;
    for(i=0; i<rows; i++)
    /* Allocate array, store pointer  */
        mat[i] = (double *) malloc(sizeof(double)*cols);

       for(i=0; i<rows; i++){
           for(j=0; j<cols; j++){
               mat[i][j] = rand() % 20 ;
           }
       }
     return mat;
}

double **create_empty_matrix(int rows, int cols){

    double **mat = (double **) malloc(sizeof(double *)*rows);
    int i=0,j=0;
    for(i=0; i<rows; i++)
    /* Allocate array, store pointer  */
        mat[i] = (double *) malloc(sizeof(double)*cols);

       for(i=0; i<rows; i++){
           for(j=0; j<cols; j++){
               mat[i][j] = 0;
           }
       }
     return mat;
}



void free_matrix(int rows, double **mat){
    int i=0;
    for(i=0;i<rows;i++)
        free(mat[i]);
    free(mat);
}

void print_matrix(int rows, int cols, double **mat){
    int i=0,j=0;
  for(i=0; i<rows; i++){    /* Iterate of each row */
        for(j=0; j<cols; j++){  /* In each row, go over each columns element  */
            printf("%lf ",mat[i][j]); /* Print each row element */
        }
        printf("\n");
    }
}

int main(){
	time_t start, stop;
	int rows, cols;
	double **a, **b, **c;
	int i, j, k;
	printf("Enter # of rows \n");
	scanf("%d",&rows);
	printf("Enter # of columns \n");
	scanf("%d",&cols);
	if(rows != cols){
		printf("Not square matrixes \n");
		return 1;
	}
	a = create_matrix(rows, cols);
	b = create_matrix(rows, cols);
	c = create_empty_matrix(rows, cols);
	printf("Multiplying Matrixes\n");
	time(&start);
	for (i=0; i < rows; i++) {
		for (j=0; j<cols; j++) {
			for (k=0; k<rows; k++) {
				c[i][j] += a[i][k] * b[k][j];
			}
		}
	}
	time(&stop);
	printf("Finished in about %.0f seconds. \n", difftime(stop, start));
/*
	printf("Matrix A \n");
	print_matrix(rows, cols, a);
	printf("Matrix B \n");
	print_matrix(rows, cols, b);
	printf("Matrix c \n");
	print_matrix(rows, cols, c);
*/
	free_matrix(rows, a);
	free_matrix(rows, b);
	free_matrix(rows, c);
	return 0;
}
